package com.wangp.mywrite.s_jvm.srljjvm.jconsole.ch1;

import java.util.ArrayList;
import java.util.List;

/***
 * @author wangpeng
 * @since 2023-03-03  16:50
 */
public class MockOOM {

    public static void main(String[] args) throws InterruptedException {
//        fillHeap(1000);
        outOfMethod();
        Thread.sleep(5000L);
    }

    public static void outOfMethod() throws InterruptedException {
        fillHeap(1000);
//        System.gc();
    }

    public static void fillHeap(int num) throws InterruptedException {
        List<OOMObject> list = new ArrayList<>();
        for (int i = 0; i < num; i++) {
            // 稍作延时，令监视曲线更明显
            Thread.sleep(50);
            list.add(new OOMObject());
        }
        // 执行System.gc()之后，空间未能回收是因为List<OOMObject>list对象仍然存活，fillHeap()方法仍然没有退出，
        // 因此list对象在System.gc()执行时仍然处于作用域之内。如果把System.gc()移动到fillHeap()方法外调用就可以回收掉全部内存。
        System.gc();
        System.out.println("done");
    }

    static class OOMObject {

        public byte[] placeholder = new byte[64 * 1024];
    }
}
